# Copyright (C) 2006  Apptility LLC  http://www.apptility.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
   include LoginEngine
   include UserEngine
   helper :user
   model :user
   layout AJUBY_CONFIG['applayout']['value']
   # TODO - make this theme selection configurable,so that users can change this
   theme AJUBY_CONFIG['apptheme']['value']
   before_filter :set_current_user_in_model, :authorize_action, :except => [:subscribefeed, :page1,:page2,:page3,:page4, :login]
   before_filter :odot_authorize_data
   
   $CURRENT_MAIN_TAB_NAME = "Dashboard"
   $list
   $data_access_actions = ["list" , "edit" , "show", "delete"]
   
  # Sets the current_user for User model, so that
  # acts_as_auditable can see current_user.
  # This is a hack for now 
  def set_current_user_in_model
    User.current_user = current_user
  end
 
   def odot_authorize_data
    controller = params["controller"]
    action = params["action"]
    if(controller!=nil and controller!='checkinstall')
    #if $data_access_actions.include?(action) and $data_access_modules.include?(controller)
      @data_auth_result = AjubyDataAuthorize.execute(controller, action, current_user, params)
      if @data_auth_result!=nil
        if action!=nil and action=='list'
          $list = @data_auth_result.list
        end
          
        if (action!=nil and  (action=='edit' or action=='delete' or action=='show'))
          @list_of_allowed = @data_auth_result.list
          @match_found = false
          if @list_of_allowed!=nil
            @id = params[:id]
            for model_obj in @list_of_allowed
              if @id == model_obj.id.to_s
                @match_found = true
                break;
              end
            end
          end  
          if @list_of_allowed==nil or @list_of_allowed.size==0 or !@match_found
              flash[:message] ="You are not allowed to #{params["action"]} this record"
              redirect_to :action=>'list'
           end
         end

      end
     end 
   end

end